package com.jf3q.securitydemo.utils;

import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;

import java.util.Collection;

/**
 * @author:xiaojie
 * @create: 2024-01-29 15:06
 * @Description:
 */


//当前登陆者有没有上面需要这些权限呢

@Component
public class MyAccessDecisionManager implements AccessDecisionManager {
    @Override
    public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes) throws AccessDeniedException, InsufficientAuthenticationException {

        for (ConfigAttribute configAttribute : configAttributes) {

            String need=configAttribute.getAttribute();

            if(need.equals("ROLE_login")){
                if (authentication instanceof AnonymousAuthenticationToken) {
                    throw  new AccessDeniedException("请登录");
                }

                return;//放行
            }

            Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();

            for (GrantedAuthority authority : authorities) {
                if (need.equals(authority.getAuthority())) {
                    return;
                }
            }


        }

        //authentication  当前登陆者的身份信息   里面就有权限



        throw  new AccessDeniedException("没有权限");

        //configAttributes 访问url需要的权限
    }

    @Override
    public boolean supports(ConfigAttribute attribute) {
        return false;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return false;
    }
}
